package com.example.myapplication2.Receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.Build;

public class SystemReceiver extends BroadcastReceiver {
    private Context context;
    private AlarmManager alarmManager;
    private PendingIntent broadcast;
    private boolean flag;
    public SystemReceiver(Context context) {
        this.context = context;
        this.flag=false;
    }

    public SystemReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("系统广播");
        if (intent!=null){
            switch (intent.getAction().toString()){
                case Intent.ACTION_TIME_TICK:
                    System.out.println("时间广播");
                    break;
                case "android.net.conn.CONNECTIVITY_CHANGE":
                    System.out.println("网络变更广播");
                    NetworkInfo networkInfo = intent.getParcelableExtra("networkInfo");
                    System.out.println(networkInfo.getTypeName());
                    break;
                case "SystemAlarm":
                    System.out.println("定时管理器执行....");
                    if (flag){
                        sendAlarm();
                    }
                    break;
            }
        }
    }
    //发送定时任务
    public void sendAlarm() {
        //获取定时任务管理器
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent("SystemAlarm");
        //延迟意图
        broadcast = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        //判定Android版本,
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //设置一次性定时任务,保证一定会执行
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,1000, broadcast);
        }else {
            //设置一次性任务,但灭屏或者关机不保证
            alarmManager.set(AlarmManager.RTC_WAKEUP,1000, broadcast);
        }

    }
    //取消定时任务
    public void cancel(){
        System.out.println("alarmManager对象"+alarmManager!=null);
        System.out.println("broadcast对象"+broadcast!=null);
        if (broadcast!=null){
            this.flag=false;
            alarmManager.cancel(broadcast);
        }
    }
    public void setLoop(){
        this.flag=!this.flag;
        System.out.println("当前循环是否启用"+this.flag);
        if (this.flag){
            sendAlarm();
        }
    }
}